#include <REGX52.H>
#include "uart.c"
#include "timer.c"
#include "game.c"
/**
 * 实现形状显示
 */
void timer0_ISR() interrupt 1
{
    if (game_frame_count < GAME_FRAME_TOTAL)
    {
        game_frame_count++;
    }
    else
    {
        game_frame_count = 0;
        // 方块下降
        // 当下方没有方块的时候，才能下降
        game_zone_remove_shape();
        if (game_check_shape_placed(game_shape.x, game_shape.y + 1, game_shape.shape))
        {
            game_shape.y++;
        }
        game_zone_add_shape();
        game_zone_display();
    }
}

void main()
{
    uart_init();
    timer0_init();
    display_init();
    game_zone_init();
    display_game_boundary();
    // GAME_ZONE[0] = 0x2F04;
    // GAME_ZONE[4] = 0x3FFC;
    game_init_shape();
    game_zone_add_shape();
    timer0_ISR_enable();
    while (1)
    {
        if (BTN_UP == 0)
        {
            while (BTN_UP == 0)
            {
            }
            timer0_ISR_disable();
            // 变形操作，新的形状能够在这个位置显示，就变形
            game_zone_remove_shape();
            if (game_check_shape_placed(
                    game_shape.x,
                    game_shape.y,
                    TETRIS_SHAPES[game_shape.shape_type][(game_shape.shape_pos + 1) % 4]))
            {
                game_shape.shape_pos = (game_shape.shape_pos + 1) % 4;
                game_shape.shape = TETRIS_SHAPES[game_shape.shape_type][game_shape.shape_pos];
            }
            game_zone_add_shape();
            timer0_ISR_enable();
        }

        if (BTN_LEFT == 0)
        {
            while (BTN_LEFT == 0)
            {
            }
            if (game_shape.x > 0)
            {
                timer0_ISR_disable();
                game_zone_remove_shape();
                if (game_check_shape_placed(
                        game_shape.x - 1,
                        game_shape.y,
                        game_shape.shape))
                {
                    game_shape.x--;
                }
                game_zone_add_shape();
                timer0_ISR_enable();
            }
        }

        if (BTN_RIGHT == 0)
        {
            while (BTN_RIGHT == 0)
            {
            }
            if (game_shape.x < 9)
            {
                timer0_ISR_disable();
                game_zone_remove_shape();
                if (game_check_shape_placed(
                        game_shape.x + 1,
                        game_shape.y,
                        game_shape.shape))
                {
                    game_shape.x++;
                }
                game_zone_add_shape();
                timer0_ISR_enable();
            }
        }
    }
}